package xh.server;

import xh.player.BasicPlayer;
import xh.player.PlayerStatusInfo;
import xh.util.Global;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2016/6/25.
 */
public class PlayerController {

    private static PlayerController instance = new PlayerController();

    BasicPlayer basicPlayer;

    ScheduledExecutorService es;

    private PlayerController() {
        basicPlayer = new BasicPlayer();

        es = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread d = new Thread(r, "t-auto-next");
                d.setDaemon(true);
                return d;
            }
        });

        es.scheduleAtFixedRate(new AutoNextTask(), 1500, 1500, TimeUnit.MILLISECONDS);

        basicPlayer.setStatusChangeListener(new BasicPlayer.StatusChangeListener() {
            public void onChange(PlayerStatusInfo playerStatusInfo) {
                ServerController.playerStatusRequestHolder().noticeUpdate(playerStatusInfo);
            }
        });
    }

    public static PlayerController controller() {
        return instance;
    }


    public void play(URL url) throws IOException {
        basicPlayer.play(url);
    }


    public void pause() {
        basicPlayer.pause();
    }


    public void restart() {
        basicPlayer.restart();
    }

    public void next() {
        URL playing = basicPlayer.getPlaying();
        URL next = randomNext(playing);
        if (next == null) {
            return;
        }

        basicPlayer.play(next);
    }

    public void volume(int v) {
        basicPlayer.adjustVolume(v);
    }

    public URL randomNext(URL last) {
        List<URL> urls = Global.musicStore.allMusicUrls();
        if (urls.size() == 0) {
            return null;
        }

        URL nextMusic;
        if (urls.size() == 1) {
            nextMusic = urls.get(0);
        } else {
            while (true) {
                int i = Global.rand(urls.size());
                if (urls.get(i).equals(last)) {
                    continue;
                }
                nextMusic = urls.get(i);
                break;
            }
        }

        return nextMusic;
    }

    public PlayerStatusInfo playerCurrentStatus() {
        return basicPlayer.statusInfo();
    }

    private class AutoNextTask implements Runnable {

        public void run() {
            if (!basicPlayer.isPlaying()) {
                next();
            }
        }
    }
}
